package ch.fhnw.qualiscan.core.db;

import org.hibernate.Session;
import org.hibernate.SessionException;

import ch.fhnw.qualiscan.core.db.HbnContainer.SessionManager;
import java.io.Serializable;
public class HibernateSession implements SessionManager, Serializable {

	public Session getSession() {
		Session currentSession;
		try {
			 currentSession = HibernateUtil.getSessionFactory().getCurrentSession();
		}
		catch(SessionException e) {
			 currentSession = HibernateUtil.getSessionFactory().openSession();
		}
		
		if (!currentSession.getTransaction().isActive()) {
			currentSession.beginTransaction();
		}
		
		/**TIMEOUT PREVENTER**/
		currentSession.createQuery("from Survey").setMaxResults(1);
		/**-----------------**/
		
		return currentSession;
	}
	
	public void closeSession() {
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
        if (sess.getTransaction().isActive()) {
            sess.getTransaction().commit();
        }
        if (sess.isOpen()) {
            sess.close();
        }
	}

}
